#!/usr/bin/env python
# coding=utf8

from datetime import datetime
import time
import json
import hashlib
import requests
import traceback
from syslog import Logger
import ConfigParser
import sys 
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法，我们需要重新载入 
sys.setdefaultencoding('utf-8') 

cf = ConfigParser.ConfigParser()
cf.read("./conf/zhongtai.ini")
logger = Logger(logger="log").getlog()

#将json 字符串排序
#strJson json字符串
#excludeParams
def orderParms(strJson, excludeParams=[]):

    arrOjb = json.JSONDecoder().decode(strJson)
    sortKey = sorted(arrOjb)
    # print sortKey
    orderStrJson = ''
    for x in sortKey:
        if x not in excludeParams:
            temp = arrOjb[x]
            if temp :
                if orderStrJson :
                    orderStrJson = orderStrJson + '&'
                orderStrJson = orderStrJson + x + '=' + temp
            else :
                pass

    return orderStrJson

#获取公共参数API_ATTRS
def  getApiAttrs(formatTimeStamp):
    apiAttrs = {}
    apiAttrs["App_Sub_ID"] = cf.get('common','App_Sub_ID')                
    apiAttrs["App_Token"] = cf.get('common','App_Token')
    apiAttrs["Api_ID"] = cf.get('getProductList','Api_ID')
    apiAttrs["Api_Version"] = cf.get('getProductList','Api_Version')
    apiAttrs["Time_Stamp"] = formatTimeStamp
    apiAttrs["User_Token"] = cf.get('common','User_Token')
    apiAttrs["Sign"] = ""
    apiAttrs["Partner_ID"] = cf.get('common','Partner_ID')
    apiAttrs["Sys_ID"] = cf.get('common','Sys_ID')

    return apiAttrs

#获取商品参数，即REQUEST_DATA
def getGoodsParms(shopId, timeStamp, page='1', pageSize="200", period="50000"):
    requestData = {}
    requestData["shopId"] = shopId
    requestData["time"] = timeStamp
    requestData["page"] = page
    requestData["pageSize"] = pageSize
    requestData["period"] = period
    requestData["status"] = '0'    #商品状态，0为正常
    # requestData["type"] = '' #商品类型
    requestData["cateL1"] = '1' #商品大分类
    #requestData["cateL2"] = '101' #商品中分类
    # requestData["cateL3"] = '' #商品小分类
    return requestData

def getSign(apiAttrsDict, requestDataDict):
    tempApiAttrsDict = apiAttrsDict
    tempApiAttrsDict['REQUEST_DATA'] = str(json.dumps(requestDataDict, ensure_ascii=False)).replace(' ', '').replace('\'', '\"')
    #要排除的字段
    excludeParams = ['Sign']
    
    strOrderParms = orderParms(json.dumps(tempApiAttrsDict, ensure_ascii=False), excludeParams) + '&' + cf.get('common','secretKey')

    objMd5 = hashlib.md5()
    objMd5.update(strOrderParms)
    del tempApiAttrsDict['REQUEST_DATA']
    return objMd5.hexdigest().upper()

def  getGoodsPostData(shopId, page='1', pageSize="100", period="50000"):
    formatTimeStamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')
    ans_time = time.mktime(time.strptime(formatTimeStamp,'%Y-%m-%d %H:%M:%S:%f'))
    timeStamp = str(ans_time)[:10] +'000'

    apiAttrsDict = getApiAttrs(formatTimeStamp)
    requestDataDict = getGoodsParms(shopId, timeStamp, page, pageSize, period)
    
    sign = getSign(apiAttrsDict, requestDataDict)
    apiAttrsDict['Sign'] = sign
    postDict = {}
    postDict['REQUEST'] = {}
    postDict['REQUEST']['API_ATTRS'] = apiAttrsDict
    postDict['REQUEST']['REQUEST_DATA'] = requestDataDict

    return postDict

def getGoodsList(shopId, page='1', pageSize="100", period="50000"):
    postData = getGoodsPostData(shopId, page, pageSize, period)

    url = cf.get("common", "Api_Url")
    headers = {"content-type": "application/json; charset=utf-8"}
    logger.info('发送数据：' + json.dumps(postData, ensure_ascii=False)) 
    # print '==========================='
    try:
        validRes = requests.post(url, data = json.dumps(postData, ensure_ascii=False), headers = headers, verify = False)
        resStr = json.JSONDecoder().decode(validRes.text)
        # print resStr
        if str(validRes.status_code) == '200' :
            validResJson = json.JSONDecoder().decode(validRes.text)
            # logger.info('接收数据：' + str(page) + '页，内容:' + json.dumps(validResJson, ensure_ascii=False)) 
            validResDict = json.loads(validRes.text)
            if validResDict['RESPONSE']['RETURN_DESC']=='success' :
                return validResDict['RESPONSE']['RETURN_DATA']['list'], validResDict['RESPONSE']['RETURN_DATA']['total']
            else:
                return 'error' + str(resStr),0
        else:
            return 'error' + str(resStr),0
    except Exception:
        logger.error('获取商品失败，异常信息：'+traceback.format_exc())
        return 'error'+traceback.format_exc(), 0

if __name__ == '__main__':
    # print(os.path.abspath(os.path.dirname(sys.argv[0])))
    # print('Tick! The time is: %s' % datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
    print(getGoodsList('BJQMD'))

    